package com.kaiyiweitong.tongxing.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kaiyiweitong.tongxing.R;
import com.kaiyiweitong.tongxing.activity.MainActivity;
import com.kaiyiweitong.tongxing.activity.classify.ServiceInfoActivity;
import com.kaiyiweitong.tongxing.activity.home.CaptureActivity;
import com.kaiyiweitong.tongxing.activity.search.SearchActivity;
import com.kaiyiweitong.tongxing.adapter.GoodServiceAdapter;
import com.kaiyiweitong.tongxing.adapter.HomeBannerAdapter;
import com.kaiyiweitong.tongxing.adapter.HomeTypeAdapter;
import com.kaiyiweitong.tongxing.adapter.MyOrderAdapter;
import com.kaiyiweitong.tongxing.constant.LogicConstant;
import com.kaiyiweitong.tongxing.fragment.home_fragment.ServiceListFragment;
import com.kaiyiweitong.tongxing.other.SpaceItemDecoration;
import com.kaiyiweitong.tongxing.util.CommonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2017/12/15 0015.
 */

public class HomeFragment extends Fragment implements ViewPager.OnPageChangeListener {
    @Bind(R.id.city)
    TextView mCity;
    @Bind(R.id.home_banner_vp)
    ViewPager mHomeBannerVp;
    @Bind(R.id.rv_home_type)
    RecyclerView mRvHomeType;
    @Bind(R.id.title_good_service)
    TextView mTitleGoodService;
    @Bind(R.id.rv_good_service)
    RecyclerView mRvGoodService;
    @Bind(R.id.title_app_platform)
    TextView mTitleAppPlatform;
    @Bind(R.id.rv_service_type)
    RecyclerView mRvServiceType;
    @Bind(R.id.vp_service_list)
    ViewPager mVpServiceList;
    @Bind(R.id.ll_good_service)
    LinearLayout mLlGoodService;
    @Bind(R.id.ll_app_platform)
    LinearLayout mLlAppPlatform;
    @Bind(R.id.ll_pic_0)
    LinearLayout mLlPic0;
    @Bind(R.id.rl_pic_1)
    RelativeLayout mRlPic1;
    @Bind(R.id.rl_pic_2)
    RelativeLayout mRlPic2;
    @Bind(R.id.rl_pic_3)
    RelativeLayout mRlPic3;
    @Bind(R.id.rl_pic_4)
    RelativeLayout mRlPic4;
    @Bind(R.id.rl_pic_5)
    RelativeLayout mRlPic5;
    @Bind(R.id.rl_pic_6)
    RelativeLayout mRlPic6;

    private final int SCAN_REQUEST_CODE = 1000;
    private static final int MOVE_MSG = 100;
    private View mView;
    private MainActivity mActivity;
    private List<Fragment> mFragments = new ArrayList<>();
    private String[] mTypes;
    private int[] mTypeIcons = new int[]{
            R.mipmap.home_type_0,
            R.mipmap.home_type_1,
            R.mipmap.home_type_2,
            R.mipmap.home_type_3,
            R.mipmap.home_type_4,
            R.mipmap.home_type_5,
            R.mipmap.home_type_6,
            R.mipmap.home_type_7,
    };
    private List<View> mPics;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_home, null);
        mActivity = (MainActivity) getActivity();
        ButterKnife.bind(this, mView);
        init();
        return mView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.ll_search, R.id.scan_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_search:
                Intent searchIntent = new Intent(mActivity, SearchActivity.class);
                startActivity(searchIntent);
                break;
            case R.id.scan_code:
                Intent scanIntent = new Intent(mActivity, CaptureActivity.class);
                startActivityForResult(scanIntent, SCAN_REQUEST_CODE);
                break;
        }
    }

    /**
     * 扫码返回
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(CaptureActivity.RESULT);
            switch (requestCode) {
                case SCAN_REQUEST_CODE:
                    if (scanResult == null || scanResult.equals("")) {
                        CommonUtil.toast(mActivity, R.string.no_data);
                    } else {
                        Pattern pattern = Pattern.compile("http(s)*://(([a-zA-z0-9]|-){1,}\\.){1,}[a-zA-z0-9]{1,}-*");
                        Matcher matcher = pattern.matcher(scanResult);
                        if (matcher.find()) { //判断扫描的结果是否为url、是url直接跳转到网页中
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse(scanResult);
                            intent.setData(content_url);
                            startActivity(intent);
                        } else {
                            CommonUtil.toast(mActivity, scanResult);
                        }
                        break;
                    }
            }
        }
    }

    private void init() {

        initVpBanner();


        mTypes = getResources().getStringArray(R.array.home_type);
        HomeTypeAdapter homeTypeAdapter = new HomeTypeAdapter(mActivity, mTypes, mTypeIcons, mTypeListener);
        mRvHomeType.setLayoutManager(new GridLayoutManager(mActivity, 4, GridLayout.VERTICAL, false));
        mRvHomeType.setAdapter(homeTypeAdapter);

        GoodServiceAdapter goodServiceAdapter = new GoodServiceAdapter(mActivity, mGoodServiceListener);
        mRvGoodService.setLayoutManager(new GridLayoutManager(mActivity, 1, GridLayout.HORIZONTAL, false));
        mRvGoodService.setAdapter(goodServiceAdapter);


        mRvServiceType.setLayoutManager(new GridLayoutManager(mActivity, 1, GridLayout.HORIZONTAL, false));
        MyOrderAdapter adapter = new MyOrderAdapter(mActivity, mTypes, mListener, mCurrentIndex);
        mRvServiceType.addItemDecoration(new SpaceItemDecoration(CommonUtil.dip2px(mActivity, 20), 2));
        mRvServiceType.setAdapter(adapter);

        if (mTypes != null && mTypes.length > 0) {
            for (int i = 0; i < mTypes.length; i++) {
                mFragments.add(ServiceListFragment.newInstance(mTypes[i]));
            }
            FragmentPagerAdapter pageAdapter = new FragmentPagerAdapter(mActivity.getSupportFragmentManager()) {
                @Override
                public int getCount() {
                    return mFragments.size();
                }

                @Override
                public Fragment getItem(int position) {
                    return mFragments.get(position);
                }
            };
            mVpServiceList.setAdapter(pageAdapter);
            if (mTypes.length > 2) {
                mVpServiceList.setOffscreenPageLimit(mTypes.length - 1);
            }
            mVpServiceList.addOnPageChangeListener(this);

            indicator(0);
        }
    }

    private void initVpBanner() {
        mPics = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            View view = LayoutInflater.from(mActivity).inflate(R.layout.banner, null);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mHomeBannerVp.getLayoutParams();
            layoutParams.height=CommonUtil.getScreenWidth(mActivity)*2/5;
            mHomeBannerVp.setLayoutParams(layoutParams);
            mPics.add(view);
        }
        HomeBannerAdapter homeBannerAdapter = new HomeBannerAdapter(mActivity, mPics);
        mHomeBannerVp.setAdapter(homeBannerAdapter);
        mHomeBannerVp.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mHandler.removeCallbacksAndMessages(null);
                        break;
                    case MotionEvent.ACTION_UP:
                        if (mPics != null && mPics.size() > 1) {
                            mHandler.sendEmptyMessageDelayed(MOVE_MSG, LogicConstant.BANNER_TIME);
                        }
                        break;
                }
                return false;
            }
        });
    }

    private HomeTypeAdapter.OnClickListener mTypeListener = new HomeTypeAdapter.OnClickListener() {
        @Override
        public void onClick(int position) {
            switch (position) {
                case 0:

                    break;
                case 1:

                    break;
                case 2:

                    break;
                case 3:

                    break;
                case 4:

                    break;
                case 5:

                    break;
                case 6:

                    break;
                case 7:

                    break;
            }
        }
    };

    private GoodServiceAdapter.OnClickListener mGoodServiceListener = new GoodServiceAdapter.OnClickListener() {
        @Override
        public void onClick(int position) {
            Intent intent = new Intent(mActivity, ServiceInfoActivity.class);

            startActivity(intent);
        }
    };


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MOVE_MSG:
                    if (mHomeBannerVp != null) {
                        if (mPics != null && mPics.size() > 1) {
                            mHomeBannerVp.setCurrentItem(mHomeBannerVp.getCurrentItem() + 1);
                            mHandler.sendEmptyMessageDelayed(MOVE_MSG, LogicConstant.BANNER_TIME);
                        }
                    }
                    break;
            }
        }
    };

    @Override
    public void onStop() {
        super.onStop();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mPics != null && mPics.size() > 1) {
            mHandler.sendEmptyMessageDelayed(MOVE_MSG, LogicConstant.BANNER_TIME);
        }
    }

    private int mCurrentIndex = -1;

    private synchronized void indicator(int position) {
        if (mCurrentIndex != position) {
            mVpServiceList.setCurrentItem(position);
            MyOrderAdapter adapter = new MyOrderAdapter(mActivity, mTypes, mListener, position);
            mRvServiceType.setAdapter(adapter);
            mRvServiceType.scrollToPosition(position);
            mCurrentIndex = position;
        }
    }

    private MyOrderAdapter.OnClickListener mListener = new MyOrderAdapter.OnClickListener() {
        @Override
        public void onClick(int position) {
            indicator(position);
        }
    };

    @Override
    public void onPageSelected(int position) {
        indicator(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }
}

